﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.IO;


using Beyondbit.Desktop.Common;
using RBS.Common;
using RBS.Common.JsonEntity;
using Webdiyer.WebControls.Mvc;

using RBS.Core.Extension;
using Model = RBS.Core.Model;
using BLL = RBS.Core.BLL;
using RBS.Web.Hotel.Service;
using RBS.Web.Hotel.Models;

namespace RBS.Web.Hotel.Controllers
{
    public class CookbookController : BaseController
    {
        private BLL.Hotel.H_Hotel_Cookbook cookBook_bll = null;

        #region Ctors

        public CookbookController() {
            cookBook_bll = new BLL.Hotel.H_Hotel_Cookbook();
        }

        #endregion

        #region 菜单列表

        /// <summary>
        /// 菜单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Cookbook(Int32 pageIndex = 1,string category="")
        {

            ViewBag.CategoryList =
                new RBS.Core.BLL.H_Hotel_CookbookCategory().GetModelList("isdisplay=0 and hotelid=" +
                                                                         CurrentUser.HotelId + " order by code asc"); 
            String keyWord = Request["kword"] ?? "";

            String strWhere = "";
            if (category == "")
            {
                 strWhere = " and [CategoryId] in(select Id from H_Hotel_CookbookCategory where [HotelId]=" + CurrentUser.HotelId + " and IsDisplay=0 )";
            }
            else
            {
                strWhere = " and [CategoryId]=" + category;
            } 
       
            if (!String.IsNullOrEmpty(keyWord)) strWhere = String.Format(" and [Name] like '%{0}%'", keyWord);

            var list = new List<RBS.Core.Model.Hotel.H_Hotel_Cookbook>();
            Int32 recordCount = 0;
            DataSet ds = cookBook_bll.GetList(10, pageIndex, strWhere, "Id desc", out recordCount);
            if (ds != null && ds.Tables[0] != null)
            {
                list.AddRange(from DataRow row in ds.Tables[0].Rows select row.ConvertToEntity<RBS.Core.Model.Hotel.H_Hotel_Cookbook>());
            }


            var pageList = new PagedList<Model.Hotel.H_Hotel_Cookbook>(list, pageIndex, 10, recordCount); 
            return View(pageList); 
        }



        public ActionResult CookbookYH(Int32 pageIndex = 1)
        {
            String keyWord = Request["kword"] ?? "";
            String strWhere = " and [CategoryId] in(select Id from H_Hotel_CookbookCategory where [HotelId]=" + CurrentUser.HotelId + " and IsDisplay=1 )";
            if (!String.IsNullOrEmpty(keyWord)) strWhere = String.Format(" and [Name] like '%{0}%'", keyWord);

            var list = new List<RBS.Core.Model.Hotel.H_Hotel_Cookbook>();
            Int32 recordCount = 0;
            DataSet ds = cookBook_bll.GetList(10, pageIndex, strWhere, "Id desc", out recordCount);
            if (ds != null && ds.Tables[0] != null)
            {
                list.AddRange(from DataRow row in ds.Tables[0].Rows select row.ConvertToEntity<RBS.Core.Model.Hotel.H_Hotel_Cookbook>());
            }
            var pageList = new PagedList<Model.Hotel.H_Hotel_Cookbook>(list, pageIndex, 10, recordCount);
            return View(pageList); 
            /*String keyWord = Request["kword"] ?? "";
            String strWhere = " and [CategoryId] in(select Id from H_Hotel_CookbookCategory where [HotelId]=" + CurrentUser.HotelId + " and IsDisplay=1)";
            if (!String.IsNullOrEmpty(keyWord)) strWhere = String.Format(" and [Name] like '%{0}%'", keyWord);

            var list = new List<RBS.Core.Model.Hotel.H_Hotel_Cookbook>();
            Int32 recordCount = 0;
            DataSet ds = cookBook_bll.GetList(10, pageIndex, strWhere, "Id desc", out recordCount);
            if (ds != null && ds.Tables[0] != null)
            {
                list.AddRange(from DataRow row in ds.Tables[0].Rows select row.ConvertToEntity<RBS.Core.Model.Hotel.H_Hotel_Cookbook>());
            }
            var pageList = new PagedList<Model.Hotel.H_Hotel_Cookbook>(list, pageIndex, 10, recordCount);
            return View(pageList);*/
        }
         

        public ActionResult SelectCookBook(Int32 pageIndex = 1)
        {  
            String keyWord = Request["kword"] ?? "";
            String strWhere = " and [CategoryId] in(select Id from H_Hotel_CookbookCategory where [HotelId]=" + CurrentUser.HotelId + " and IsDisplay=0 )";
            if (!String.IsNullOrEmpty(keyWord)) strWhere = String.Format(" and [Name] like '%{0}%'", keyWord);

            var list = new List<RBS.Core.Model.Hotel.H_Hotel_Cookbook>();
            Int32 recordCount = 0;
            DataSet ds = cookBook_bll.GetList(10, pageIndex, strWhere, "Id desc", out recordCount);
            if (ds != null && ds.Tables[0] != null)
            {
                list.AddRange(from DataRow row in ds.Tables[0].Rows select row.ConvertToEntity<RBS.Core.Model.Hotel.H_Hotel_Cookbook>());
            }
            var pageList = new PagedList<Model.Hotel.H_Hotel_Cookbook>(list, pageIndex, 10, recordCount); 
            return View(pageList); 
        }
         

        /// <summary>
        /// 菜单列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public ActionResult CookbookList(Int32 pageIndex = 1) { 

            var list = new List<RBS.Core.Model.Hotel.H_Hotel_Cookbook>();
            Int32 recordCount =0;
            DataSet ds = cookBook_bll.GetList(10, pageIndex, "", "Id", out recordCount);
            if (ds != null && ds.Tables[0] != null) {
                foreach (DataRow row in ds.Tables[0].Rows) {
                    var entity = row.ConvertToEntity<RBS.Core.Model.Hotel.H_Hotel_Cookbook>();
                    list.Add(entity);
                }
            }
            PagedList<RBS.Core.Model.Hotel.H_Hotel_Cookbook> pageList = new PagedList<Model.Hotel.H_Hotel_Cookbook>(list, pageIndex, 10, recordCount);
            
            return View("_CookbookList", pageList);
        }

        #endregion

        #region 菜单新增|编辑|删除

        /// <summary>
        /// 菜单编辑View
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult CookbookEdit(int id = 0)
        {
            var model = new RBS.Core.Model.Hotel.H_Hotel_Cookbook
                {
                    CookingNumber=1,
                    CookingWeights="100",
                    EstimateClear = "-1"
                }; 
            if (id != 0)
            { 
                var bll = new RBS.Core.BLL.Hotel.H_Hotel_Cookbook();
                model = bll.GetModel(id);
                ViewBag.BeforeAndAfter = bll.GetBeforeAndAfter(CurrentUser.HotelId, id).Tables[0].Rows[0];
            }
            //菜谱分类
            ViewBag.Category = new SelectList(CategoryBind(model.CategoryId,CurrentUser.HotelId,0), "Value", "Text",model.CategoryId);  
            //菜系

            //单位
            ViewBag.CBUnits = new SelectList(CookBookService.Instance.GetCookBookUnitList(), "Name", "Name", "");

            ViewData.Model = model;
            return View();
        }

        /// <summary>
        /// 菜单编辑
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CookbookEdit(FormCollection collection)
        {
            var a = collection;
            var model = new RBS.Core.Model.Hotel.H_Hotel_Cookbook
            {
                Name = collection["Name"],
                Price = Convert.ToDecimal(collection["Price"]),
                Species = collection["Species"],
                Unit = collection["Unit"],
                Component = collection["Component"],
                DishImages = collection["DishImages"],
                CookingWeights = collection["CookingWeights"],
                Permissions = collection["Permissions"],
                GoodCook = collection["GoodCook"],
                Special ="0",
                Cuisine = collection["Cuisine"],
                Discount = Convert.ToDecimal(collection["Discount"]),
                EstimateClear = collection["EstimateClear"],
                CookingNumber = Convert.ToInt32(collection["CookingNumber"]),
                StartIdentification = Convert.ToInt32(collection["StartIdentification"]),
                CategoryId = Convert.ToInt32(collection["CategoryId"])
            };

            var bll = new RBS.Core.BLL.Hotel.H_Hotel_Cookbook();
            if (collection["Id"] != "0")
            {
                model.Id = Convert.ToInt32(collection["Id"]);
                bll.Update(model);
            }
            else
            {
                bll.Add(model);
            }
            return RedirectToAction("Cookbook");
        }

        //
        /// <summary>
        /// 菜单编辑View
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult CookbookYHEdit(int id = 0)
        {
            var model = new RBS.Core.Model.Hotel.H_Hotel_Cookbook
            {
                CookingNumber = 1,
                CookingWeights = "100",
                EstimateClear = "-1"
            };  
            if (id != 0)
            {
                var bll = new RBS.Core.BLL.Hotel.H_Hotel_Cookbook();
                model = bll.GetModel(id);
            }
            //菜谱分类
            ViewBag.Category = new SelectList(CategoryBind(model.CategoryId, CurrentUser.HotelId,1), "Value", "Text", model.CategoryId);
            //菜系

            //单位
            ViewBag.CBUnits = new SelectList(CookBookService.Instance.GetCookBookUnitList(), "Name", "Name", "");

            ViewData.Model = model;
            return View();
        }

        /// <summary>
        /// 菜单编辑
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CookbookYHEdit(FormCollection collection)
        {
            var a = collection;
            var model = new RBS.Core.Model.Hotel.H_Hotel_Cookbook
            {
                Name = collection["Name"],
                Price = Convert.ToDecimal(collection["Price"]),
                Species = collection["Species"],
                Unit = collection["Unit"],
                Component = collection["Component"],
                DishImages = collection["DishImages"],
                CookingWeights = collection["CookingWeights"],
                Permissions = collection["Permissions"],
                GoodCook = collection["GoodCook"],
                Special = collection["Special"],
                Cuisine = collection["Cuisine"],
                Discount = Convert.ToDecimal(collection["Price"]),
                EstimateClear ="-1",
                CookingNumber = Convert.ToInt32(collection["CookingNumber"]),
                StartIdentification = Convert.ToInt32(collection["StartIdentification"]),
                CategoryId = Convert.ToInt32(collection["CategoryId"])
            };

            var bll = new RBS.Core.BLL.Hotel.H_Hotel_Cookbook();
            if (collection["Id"] != "0")
            {
                model.Id = Convert.ToInt32(collection["Id"]);
                bll.Update(model);
            }
            else
            {
                bll.Add(model);
            }
            return RedirectToAction("CookbookYH");
        } 


        /// <summary>
        /// 菜单删除
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult CookbookDelete(string ids, string returnUrl)
        {
            var ret = new JsonReturnMessages();

            try
            {
                foreach (var id in ids.TrimEnd(',').Split(',').ToList())
                {
                    new RBS.Core.BLL.Hotel.H_Hotel_Cookbook().Delete(int.Parse(id));
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = "操作失败！";
                return Json(ret);
            }

            ret.IsSuccess = true;
            ret.Msg = "操作成功";
            ret.Data = !string.IsNullOrEmpty(returnUrl) ? returnUrl : Url.Action("AdminUserManager", "Sys");
            return Json(ret);
        }

        #region 获取菜系tree

        /// <summary>
        /// 获取菜系tree
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetCaiXiTree() {

            IList<CookBookCaiXiViewModel> list = CookBookService.Instance.GetCookBookCaiXiList();
            IList<Object> treeList = new List<Object>();
            foreach (var item in list)
            {
                treeList.Add(new
                {
                    id = item.ID,
                    text = item.Name,
                    children = getChildCaiXiTree(item.Childs)
                });
            }

            return Json(treeList);
        }

        /// <summary>
        /// 递归获取子菜谱tree
        /// </summary>
        /// <param name="sourceList"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private List<Object> getChildCaiXiTree(IList<CookBookCaiXiViewModel> sourceList)
        {
            if (sourceList == null || sourceList.Count <= 0) return null;

            List<Object> list = new List<object>();
            foreach (var item in sourceList)
            {
                list.Add(new
                {
                    id = item.ID,
                    text = item.Name,
                    children = getChildCaiXiTree(item.Childs)
                });
            }

            return list;
        }

        #endregion

        #region 图片上传

        /// <summary>
        /// 菜谱图片上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UploadImg()
        {
            var ret = new JsonImgMsg();
            string outpath = "UploadImages" + "\\" + "Hotels\\" + CurrentUser.HotelId + "\\Cookbook\\";
            string physicalPath = HttpContext.Server.MapPath("~/") + outpath;
            if (!Directory.Exists(physicalPath))
                Directory.CreateDirectory(physicalPath);
            try
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    var httpPostedFileBase = Request.Files[0];
                    if (httpPostedFileBase != null)
                    {
                        var postedFileBase = Request.Files[i];
                        if (postedFileBase != null)
                        {
                            string filename = DateTime.Now.ToString("yyyyMMddhhmmss") +
                                              System.IO.Path.GetExtension(postedFileBase.FileName);
                            httpPostedFileBase.SaveAs(physicalPath + filename);
                            ret.name = filename;
                            ret.thumb = physicalPath;
                            ret.path = outpath + filename;
                            ret.size = postedFileBase.ContentLength;
                            ret.ext = System.IO.Path.GetExtension(postedFileBase.FileName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ret.status = 0;
                ret.msg = "上传过程中发生意外错误！";
                return Json(ret);
            }
            ret.status = 1;
            ret.msg = "上传文件成功！";
            return Json(ret);
        }

        #endregion

        #endregion

        #region 菜谱分类管理 Category
        protected List<SelectListItem> CategoryBind(int categoryId,int hotelId, int isDisplay)
        { 
            var bll = new RBS.Core.BLL.H_Hotel_CookbookCategory(); 
            //如果新增酒店，则新增默认菜谱分类
            if (!bll.ExistsHotelId(hotelId))
            {
                #region 添加默认菜谱分类 
                var model = new RBS.Core.Model.Hotel.H_Hotel_CookbookCategory
                {
                    Name = "热菜",
                    Code = "recai",
                    Parentid = 0,
                    HotelId = hotelId,
                    RoleId = "0",
                    IsDisplay = 0
                };
                bll.Add(model);
                  model = new RBS.Core.Model.Hotel.H_Hotel_CookbookCategory
                {
                    Name = "凉菜",
                    Code = "liangcai",
                    Parentid = 0,
                    HotelId = hotelId,
                    RoleId = "0",
                    IsDisplay = 0
                };
                bll.Add(model);
                  model = new RBS.Core.Model.Hotel.H_Hotel_CookbookCategory
                {
                    Name = "汤",
                    Code = "tang",
                    Parentid = 0,
                    HotelId = hotelId,
                    RoleId = "0",
                    IsDisplay = 0
                };
                bll.Add(model);
                  model = new RBS.Core.Model.Hotel.H_Hotel_CookbookCategory
                {
                    Name = "主食",
                    Code = "zhushi",
                    Parentid = 0,
                    HotelId = hotelId,
                    RoleId = "0",
                    IsDisplay = 0
                };
                bll.Add(model);
                 model = new RBS.Core.Model.Hotel.H_Hotel_CookbookCategory
                {
                    Name = "酒水",
                    Code = "jiusui",
                    Parentid = 0,
                    HotelId = hotelId,
                    RoleId = "0",
                      IsDisplay = 0
                };
                bll.Add(model);
                model = new RBS.Core.Model.Hotel.H_Hotel_CookbookCategory
                {
                    Name = "即时消费品",
                    Code = "jsxhp",
                    Parentid = 0,
                    HotelId = hotelId,
                    RoleId = "0",
                    IsDisplay = 1
                };
                bll.Add(model);
                #endregion
            }
            DataTable dt = bll.GetList(" HotelId = " + hotelId + " and isDisplay=" + isDisplay).Tables[0];   
            var selectListItems = new List<SelectListItem>(); 
            selectListItems.Clear();
           // selectListItems.Add(new SelectListItem { Text = "请选择类型", Value = "0" });
            selectListItems.AddRange(from DataRow dr in dt.Rows
                                     let Id = dr["id"].ToString() 
                                     let title = dr["Name"].ToString().Trim()
                                     select Id == categoryId.ToString() ? new SelectListItem { Text = title, Value = Id, Selected = true } : new SelectListItem { Text = title, Value = Id });
            return selectListItems;
        }

        public ActionResult CookbookCategoryList(int id = 1, string kword = null)
        {
            const int pageSize = 10;

            var bll = new RBS.Core.BLL.H_Hotel_CookbookCategory();  
           // var admin = GetAdminInfo(); //取得当前管理员信息
            if (kword != null) kword = kword.Replace("'", "");
            var strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(kword))
            {
                //strTemp.Append(" and (H_UID like  '%" + kword + "%' or H_UserName like '%" + kword + "%')");
            }
            string strWhere = "and HotelId="+CurrentUser.HotelId+ strTemp.ToString();
            const string orderby = " Code asc";
            var startIndex = id;

            int totalItems = 0; //要分页的总记录数
            DataTable dt = bll.GetList(pageSize, startIndex, strWhere, orderby, out totalItems).Tables[0];
            //PagedList构造函数 
            var list = IListDataSet.DataTableToIList<RBS.Core.Model.Hotel.H_Hotel_CookbookCategory>(dt);
            PagedList<RBS.Core.Model.Hotel.H_Hotel_CookbookCategory> arts = null;
            if(list!=null)
              arts = new PagedList<RBS.Core.Model.Hotel.H_Hotel_CookbookCategory>(list, id, pageSize, totalItems);
            else
            {
                list = new List<RBS.Core.Model.Hotel.H_Hotel_CookbookCategory>();
                arts = new PagedList<RBS.Core.Model.Hotel.H_Hotel_CookbookCategory>(list, id, pageSize, totalItems);  
            } 
            return View(arts);
        }
		//edit
        public ActionResult CookbookCategoryEdit(int id = 0)
        { 
            var model = new RBS.Core.Model.Hotel.H_Hotel_CookbookCategory();
            model.HotelId = CurrentUser.HotelId;
            if (id != 0)
            { 
                var bll = new RBS.Core.BLL.H_Hotel_CookbookCategory();
                model = bll.GetModel(id);
            } 
            ViewData.Model = model; 
            return View();
        }
        [HttpPost]
        public ActionResult CookbookCategoryEdit(FormCollection collection)
        { 
            var a = collection;
            var model = new  RBS.Core.Model.Hotel.H_Hotel_CookbookCategory
                {
                    Name =  collection["Name"],
                    Code =  collection["Code"],
                    Parentid = Convert.ToInt32(collection["Parentid"]),
                    HotelId = Convert.ToInt32(collection["HotelId"]),
                    RoleId = collection["RoleId"],
                    IsDisplay = Convert.ToInt32(collection["IsDisplay"]),
                }; 
            
            var bll = new RBS.Core.BLL.H_Hotel_CookbookCategory();
            if (collection["Id"] != "0")
            {
                model.Id = Convert.ToInt32(collection["Id"]);
                bll.Update(model); 
            }
            else
            { 
                bll.Add(model);
            } 
            if (Request["type"] != null)
            {
                return RedirectToAction("CookbookCategoryList");
            }
            return RedirectToAction("CookbookEdit");
        } 
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult CookbookCategoryDelete(string ids, string returnUrl)
        {
            var ret = new JsonReturnMessages(); 
            try
            {
                 
                foreach (var id in ids.TrimEnd(',').Split(',').ToList())
                {
                  var b=  new RBS.Core.BLL.H_Hotel_CookbookCategory().Delete(int.Parse(id));
                    if (!b)
                    {
                        ret.Data += id + ",";

                    }
                }

                if (ret.Data == null)
                {
                    ret.IsSuccess = true;
                    ret.Msg = "操作成功";
                    ret.Data = !string.IsNullOrEmpty(returnUrl) ? returnUrl : Url.Action("CookbookCategoryList");
                }
                else
                {
                    ret.IsSuccess = false;
                    ret.Msg = "部分数据删除失败，当前分类下面存在菜谱信息！";
                    ret.Data = !string.IsNullOrEmpty(returnUrl) ? returnUrl : Url.Action("CookbookCategoryList");
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = "操作失败！";
                return Json(ret);
            } 
       
            return Json(ret);
        }


        /// <summary>
        /// 判断编码唯一
        /// </summary>
        /// <param name="param"></param>
        /// <param name="cid"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult CheckCookCategoryCode(string param, string cid)
        {
            var model = new CheckModel();
            DataTable dt  = new RBS.Core.BLL.H_Hotel_CookbookCategory().GetList(" HotelId=" + CurrentUser.HotelId + "and Code='" + param + "'"+ "and Id<>'"+cid+"'").Tables[0];

             if (dt != null && dt.Rows.Count > 0)
             {
                 model.info = "验证不通过，数据已存在";
                 model.status = "n";
             }
             else
             {
                 model.info = "验证通过";
                 model.status = "y";
             }
            return Json(model);
        } 

        #endregion

    }
}
